package com.zdkj.subway.st.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.support.atomic.RedisAtomicLong;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.concurrent.TimeUnit;

/**
 * @ProjectName: zdkj
 * @Package: com.zdkj.subway.st.util
 * @ClassName: CacheService
 * @Description:
 * @Author: kangjian
 * @CreateDate: 2020/2/7 11:19
 * @Version: 1.0
 */
@Component
public class CacheService {

    @Autowired
    private RedisTemplate redisTemplate;

    public Long getIncrementNum(String key) {
        // 不存在准备创建 键值对
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key,redisTemplate.getConnectionFactory());
        Long counter = entityIdCounter.incrementAndGet();
        if ((null == counter || counter.longValue() == 1)) {// 初始设置过期时间
            //设置过期时间为1天
            entityIdCounter.expire(1, TimeUnit.DAYS);// 单位天
        }
        return counter;
    }

    public Long getIncrementNumYear(String key) {
        // 不存在准备创建 键值对
        RedisAtomicLong entityIdCounter = new RedisAtomicLong(key,redisTemplate.getConnectionFactory());
        Long counter = entityIdCounter.incrementAndGet();
        if ((null == counter || counter.longValue() == 1)) {// 初始设置过期时间
            //根据当前年判断还剩多少天
            Calendar calendar = Calendar.getInstance();
            int timeout = calendar.getActualMaximum(Calendar.DAY_OF_YEAR) - calendar.get(Calendar.DAY_OF_YEAR);
            //设置过期时间为首次开始计算剩余天数
            entityIdCounter.expire(timeout, TimeUnit.DAYS);// 单位天
        }
        return counter;
    }

}
